﻿using System.Collections;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

public class PauseMenu : MonoBehaviour
{
    [SerializeField] Button exitMenuBT;
    [SerializeField] Button exitGameBT;
    [SerializeField] Button closeBT;
    
    private void Start()
    {        
        exitGameBT.onClick.AddListener(ExitGame);
        exitMenuBT.onClick.AddListener(ExitToMenu);
        closeBT.onClick.AddListener(OnClose);
    }

    private void OnEnable()
    {
        if (GameManager.Instance.IsSinglePlay)
            StartCoroutine(SetTimeScale(0f));
    }

    private void OnDisable()
    {
        StopAllCoroutines();
        if (GameManager.Instance.IsSinglePlay)
            Time.timeScale = 1f;
    }

    IEnumerator SetTimeScale(float scale)
    {
       yield return new WaitForEndOfFrame();
         Time.timeScale = scale;
    }

    public void OnHandleInput()
    {        
        if (gameObject.activeInHierarchy)
            OnClose();
        else
            OnOpen();
    }

    public void OnOpen()
    {
        Debug.Log("on open");
        gameObject.SetActive(true);                    
    }

    void OnClose()
    {        
        Debug.Log("on close");
        gameObject.SetActive(false);
    }    

    void ExitToMenu()
    {
        GameManager.Instance.GameOver();
        OnClose();
    }

    void ExitGame()
    {
        ConnectionManager.Instance.ShutDown();
#if UNITY_EDITOR        
        EditorApplication.isPlaying = false;
#else            
        Application.Quit();
#endif
    }
}